package it.fc.action.giocatori;

import fc.utils.FcCostanti;
import it.fc.action.FcAction;
import it.fc.bean.SquadraBean;
import it.fc.service.interfaces.IDbService;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class SaveTeamAction extends FcAction {

    private static final long serialVersionUID = 8273631969224468328L;
    private static Logger     log              = Logger.getLogger(SaveTeamAction.class);
    private String            playersId;
    private String            nome;

    @Override
    public String execute() throws Exception {
        log.debug("Saving.... : " + getPlayersId());

        List<Integer> team = getListId();
        IDbService dbManager = getDbService();
        
        

        int idSquadra = ((SquadraBean) dbManager.getSquadraByUser(getIdUser())).getIdSquadra();

        if (idSquadra > 0) {
            dbManager.deleteCalciatori(idSquadra);
        }

        int costoTeam = dbManager.insertCalciatori(idSquadra, team);

        log.debug("Save team a costo " + costoTeam);

        // aggiorno il budget
        getUser().setBudget(FcCostanti.COSTO_TEAM - costoTeam);
        dbManager.updateUser(getUser());

        return SUCCESS;
    }

    private List<Integer> getListId() {
        StringTokenizer strTkz = new StringTokenizer(getPlayersId());

        List<Integer> giocatori = new ArrayList<Integer>();

        while (strTkz.hasMoreElements()) {
            Integer elem = Integer.parseInt(strTkz.nextToken("|"));
            giocatori.add(elem);
            log.debug("Add elem " + elem + " ... ");
        }

        return giocatori;
    }

    public String getPlayersId() {
        return playersId;
    }

    public void setPlayersId(String playersId) {
        this.playersId = playersId;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

}
